package com.example.reflect.demo08.annotation;

import java.lang.reflect.Field;

public class Demo {
    public static void main(String[] args) {
        Demo demo=new Demo();
        try {
            Person person=new Person();
            person.setName("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            person.setCity("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            demo.check(person);
        } catch (ReflectiveOperationException e) {
            System.out.println(e.getMessage());
        }
    }

    void check(Person person) throws IllegalArgumentException, ReflectiveOperationException {
        // 遍历所有Field:
        for (Field field : person.getClass().getFields()) {
            // 获取Field定义的@Range:
            Range range = field.getAnnotation(Range.class);
            // 如果@Range存在:
            if (range != null) {
                // 获取Field的值:
                Object value = field.get(person);
                // 如果值是String:
                if (value instanceof String) {
                    String s=(String)value;
                    // 判断值是否满足@Range的min/max:
                    if (s.length() < range.min() || s.length() > range.max()) {
                        throw new IllegalArgumentException("Invalid field: " + field.getName()+" is "+s.length()+",but it max "+range.max()+" and min "+range.min());
                    }
                }
            }
        }
    }

}
